package com.rzico.sbl.ui.statistic

import android.view.inputmethod.EditorInfo
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityStockBarrelBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.model.StockBarrel
import com.rzico.sbl.other.showStockDialog
import com.rzico.sbl.viewmodel.StatisticStockViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionElse
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.goneValue
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.orEmpty
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.textTrim
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.addOnScrollChanged
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.showListDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class StockBarrelActivity : BaseActivity(R.layout.activity_stock_barrel) {

    private val mBinding by lazy { ActivityStockBarrelBinding.bind(getRootView()) }

    private val mShopList = arrayListOf<FilterData>()
    private val mBrandList = ArrayList<FilterData>()
    private var mKeyWord = ""
    private var mShopId = ""

    override fun getViewModel() = get<StatisticStockViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        getShopList()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .emptyHint
                    .text = "暂无相关空桶信息！"

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(hasHeader = false, bottom = 60f))
                    layout.addOnScrollChanged(
                        onShow = { mBinding.barrelBottom.bottomShow() },
                        onHide = { mBinding.barrelBottom.bottomHide(55f) }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<StockBarrel>(R.layout.item_stock_barrel) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_stock_name, bean.name)
                                text(R.id.item_stock_code, bean.barrelId)
                                text(R.id.item_stock_stock, bean.quantity)

                                visibility(
                                    R.id.item_stock_jian,
                                    goneValue { bean.quantity.intValue == 0 }
                                )

                                clicked(R.id.item_stock_jian) {
                                    decreaseStock(bean.id, bean.name)
                                }

                                clicked(R.id.item_stock_jia) {
                                    increaseStock(bean.id, bean.name)
                                }

                                clicked {
                                    startActivityEx<StockRecordActivity>(
                                        "stockId" to bean.id
                                    )
                                }

                                longClicked {
                                    deleteBarrel(bean.id, index)
                                    true
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .barrelSearch
            .apply {
                searchEdit.hint = "请输入空桶品牌"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        (it.isEmpty() && mKeyWord.isNotEmpty())
                            .condition {
                                mKeyWord = ""
                                updateList()
                            }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    (actionId == EditorInfo.IME_ACTION_SEARCH)
                        .condition {
                            hideSoftInput() //隐藏软键盘

                            searchEdit.text
                                .isBlank()
                                .conditionElse(
                                    actionTrue = { showToast("请输入空桶品牌") },
                                    actionFalse = {
                                        mKeyWord = searchEdit.textTrim
                                        updateList()
                                    }
                                )
                        }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    searchEdit.text
                        .isBlank()
                        .conditionElse(
                            actionTrue = { showToast("请输入空桶品牌") },
                            actionFalse = {
                                mKeyWord = searchEdit.textTrim
                                updateList()
                            }
                        )
                }
            }
    }

    override fun initListener() {
        mBinding
            .btAdd
            .oneClick {
                getBrandList {
                    showListDialog(
                        title = "请选择品牌",
                        items = mBrandList.map { it.name },
                        listener = { index, _ ->
                            val itemId = mBrandList[index].id

                            mList.any {
                                it as StockBarrel
                                it.barrelId == itemId
                            }.condition {
                                showToast("仓库已添加该品牌，请重新选择")
                                return@showListDialog
                            }

                            getViewModel()
                                .requestBind(
                                    requestUrl = BaseUrl.psiBarrelAdd,
                                    params = arrayOf(
                                        "shopId" to mShopId,
                                        "ids" to itemId
                                    )
                                )
                                .bindLifeCycle(getLifecycleOwner())
                                .subscribeBySuccess(
                                    event = getViewModel(),
                                    onSuccess = {
                                        showToast("添加成功！")

                                        updateList()
                                    }
                                )
                        }
                    )
                }
            }

        mBinding
            .barrelShop
            .apply {
                timeHint.text = "仓库名称"

                timeLayout
                    .oneClick {
                        getViewModel()
                            .showDropFilter(
                                getIContext(),
                                timeLayout,
                                mShopList,
                                timeHint,
                                timeHintArrow,
                            ) { bean ->
                                mShopId = bean.id

                                updateList()
                            }
                    }
            }
    }

    /**
     * 增加空桶库存
     */
    private fun increaseStock(itemId: String, name: String) {
        showStockDialog(
            name = name,
            type = 1,
            isForced = true,
            onSelect = { view, arr ->
                mPosition = 0

                showListDialog(
                    title = "请选择事由",
                    items = getViewModel().reasonIn(),
                    index = mPosition,
                    listener = { index, hint ->
                        mPosition = index
                        view.text = hint
                        arr[0] = hint
                    }
                )
            },
            onSure = { reason, num, memo ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.psiStock,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to itemId,
                            "action" to 0,
                            "quantity" to num,
                            "subject" to reason,
                            "memo" to memo
                        ),
                        onSuccess = {
                            showToast("库存修改成功！")

                            updateList()
                        }
                    )
            }
        )
    }

    /**
     * 减少空桶库存
     */
    private fun decreaseStock(itemId: String, name: String) {
        showStockDialog(
            name = name,
            type = 2,
            isForced = true,
            onSelect = { view, arr ->
                mPosition = 0

                showListDialog(
                    title = "请选择事由",
                    items = getViewModel().reasonOut(),
                    index = mPosition,
                    listener = { index, hint ->
                        mPosition = index
                        view.text = hint
                        arr[0] = hint
                    }
                )
            },
            onSure = { reason, num, memo ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.psiStock,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to itemId,
                            "action" to 1,
                            "quantity" to num,
                            "subject" to reason,
                            "memo" to memo
                        ),
                        onSuccess = {
                            showToast("库存修改成功！")

                            updateList()
                        }
                    )
            }
        )
    }

    /**
     * 删除空桶
     */
    private fun deleteBarrel(itemId: String, index: Int) {
        showHintDialog(
            title = "删除空桶",
            hint = "确定要删除该空桶和库存吗？",
            sure = "删除",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngPickProD,
                        params = arrayOf("ids" to itemId),
                        onSuccess = {
                            showToast("空桶删除成功！")

                            mList.removeAt(index)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, mList.size - index)
                            }

                            mBinding.listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 获取空桶品牌
     */
    private fun getBrandList(onNext: () -> Unit) {
        mBrandList
            .isNotEmpty()
            .conditionElse(
                actionTrue = onNext,
                actionFalse = {
                    getViewModel()
                        .requestCommon(
                            isLoading = true,
                            requestUrl = BaseUrl.bucketPdt,
                            requestMethod = HttpMethod.GET,
                            onSuccess = { list ->
                                mBrandList.clear()
                                list.notEmpty {
                                    mapTo(mBrandList) {
                                        FilterData(
                                            id = it.id,
                                            name = it.name.orEmpty()
                                        )
                                    }
                                }
                            },
                            onFinally = onNext
                        )
                }
            )
    }

    /**
     * 获取店铺列表，含自提点
     */
    private fun getShopList() {
        getViewModel()
            .shopList(
                onSuccess = { list ->
                    mShopList.clear()
                    list.notEmpty {
                        mapTo(mShopList) {
                            FilterData(
                                it.shopName.orEmpty(),
                                it.id,
                                it.shopName.orEmpty()
                            )
                        }
                    }

                    mShopId = mShopList[0].id
                    mShopList[0].isChecked = true

                    mBinding.apply {
                        barrelShop
                            .timeHint
                            .text = mShopList[0].name

                        listLayout
                            .swipeRefresh
                            .isRefreshing = true
                    }
                },
                onFinally = { getData(pageNum) }
            )
    }

    /**
     * 空桶库存列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .barrelList(
                page = index,
                shopId = mShopId,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it.data)
                        it.data.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)

                    mBinding.apply {
                        barrelCount.text = it.summary?.subTotal.orEmpty("0")
                        barrelNum.text = it.summary?.subQuantity.orEmpty("0")
                    }
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}